# coding=utf-8
from datetime import datetime
from uuid import uuid4

from common import orm
from common.mch.db import encode_password
from common.mch.model import MchAccount, MchChannel
from common.utils import track_logging
from common.utils.db import list_object, get, upsert, delete
from common.utils.decorator import sql_wrapper

_LOGGER = track_logging.getLogger(__name__)

DEFAULT_PASSWD = '123456'
SERVICE_MAP = ["alipay", "jd", "qq", "wechat", "unionpay", "withdraw_alipay", "wxapp","recharge_card", "test",
               'quota_alipay', 'quota_wxpay', 'qr_alipay', 'cloud_flash', 'hydra', 'quota_hydra']


@sql_wrapper
def get_mch(id):
    return get(MchAccount, id)


@sql_wrapper
def upsert_mch(info, id=None):
    return upsert(MchAccount, info, id)


@sql_wrapper
def create_mch(info, id=None):
    if 'password' not in info:
        info['password'] = encode_password(DEFAULT_PASSWD)
    if 'api_key' not in info or not info['api_key']:
        info['api_key'] = uuid4().hex
    return upsert(MchAccount, info, id)


@sql_wrapper
def list_mch(query_dct):
    return list_object(query_dct, MchAccount)


@sql_wrapper
def delete_mch(id):
    delete(MchAccount, id)


@sql_wrapper
def get_mch_chn(id):
    return get(MchChannel, id)


@sql_wrapper
def upsert_mch_chn(info, mch_id, service_name):
    mch_chn = MchChannel.query.filter(MchChannel.mch_id == mch_id).filter(
        MchChannel.service_name == service_name).first()
    id = mch_chn.id if mch_chn else None
    return upsert(MchChannel, info, id)


@sql_wrapper
def modify_mch_chn(info, mch_id):
    for k, v in info.iteritems():
        if k in SERVICE_MAP:
            mch_chn = MchChannel.query.filter(MchChannel.mch_id == mch_id).filter(
                MchChannel.service_name == k).first()
            if mch_chn is None:
                continue
            mch_chn.chns = ','.join(str(x) for x in v)
            mch_chn.save()


@sql_wrapper
def update_mch_chn(mch_id, service_name, info):
    info.update(updated_at=datetime.utcnow())
    MchChannel.query.filter(MchChannel.mch_id == mch_id).filter(
        MchChannel.service_name == service_name).update(info)
    orm.session.commit()


@sql_wrapper
def list_mch_chn(query_dct):
    return list_object(query_dct, MchChannel)


@sql_wrapper
def delete_mch_chn(id):
    delete(MchChannel, id)


@sql_wrapper
def get_mch_chns(mch_id):
    mch_chns = MchChannel.query.filter(MchChannel.mch_id == mch_id).all()
    l = []
    for m in mch_chns:
        if 'withdraw' not in m.service_name:
            for c in m.chns.split(','):
                l.append(c)
    return l
